package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BeasContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: 许志民
 * Date: 2021-11-22
 */
@WebFilter(filterName = "checkFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器 支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到请求：{}", request.getRequestURI());
        //获取本次请求的URI
        String uri = request.getRequestURI();
        //判断此次请求是否需要放行
        String[] uris = new String[]{
                "/employee/login",
                "/backend/page/login/login.html",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "swagger-ui.html"
        };
        if (check(uri, uris)) {
            //如果达到放行要求则放行否则不通过
            filterChain.doFilter(request, response);
            //放行之后结束本方法
            log.info("放行");
            return;
        }
        //如果不是登录请求首先看用户是否登录
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        //如果为查找到id，则表示用户尚未登录，则重定向到登录界面
        if (employee != null) {
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            //用户一登录则放行
            BeasContext.setCurrentId(employee);
            filterChain.doFilter(request, response);
            return;

        }
        Long user = (Long) session.getAttribute("user");
        if(user != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //用户一登录则放行
            BeasContext.setCurrentId(user);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public boolean check(String uri, String[] uris) {
        for (String url : uris) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
